

// const EN_CLASS = new Map()
// EN_CLASS.set('Connector', Connector)
// EN_CLASS.set('User', User);
// EN_CLASS.set('PointRoom', PointRoom);
// EN_CLASS.set('PoolRoom', PoolRoom);
// EN_CLASS.set('PrivateRoom', PrivateRoom);

import GameDataUtilTs from "./GameDataUtilTs";

cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //     // ATTRIBUTES:
        //     default: null,        // The default value will be used only when the component attaching
        //                           // to a node for the first time
        //     type: cc.SpriteFrame, // optional, default is typeof default
        //     serializable: true,   // optional, default is true
        // },
        // bar: {
        //     get () {
        //         return this._bar;
        //     },
        //     set (value) {
        //         this._bar = value;
        //     }
        // },
    },

    ctor(){
        // this.rootUrl = "https://api.khelochalo.com:20031"    //线上服务器
        this.rootUrl = 'https://api.khelochalo.com:20035'     //线上正式signalr服务器
        // this.rootUrl = 'https://api.khelochalo.com:20045'     //signalr测试服务器
        this.panImgUrl = 'https://api.khelochalo.com:20040/pan/img/upload'

        let useTestServer = GameDataUtilTs.getUseTestServer() || 0
        if(!useTestServer){
            let channel = this.getPakageChannel()
            if(channel === "fb2"){
                this.rootUrl = 'https://api.khelochalo.com:20035'     //正式fb2服务器
            }else {
                this.rootUrl = 'https://api.khelochalo.com:20036'     //正式其他服务器
            }

        }else {
            this.rootUrl = 'https://api.khelochalo.com:20045'     //测试服务器
        }

        if(CC_DEBUG){
            this.rootUrl = 'https://api.khelochalo.com:20035'
        }
    },

    getPakageChannel:function () {

        if(cc.sys.isNative && cc.sys.os == cc.sys.OS_ANDROID){
            var channel = jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "getChannel","()Ljava/lang/String;");
            console.log("渠道：",channel)
            return channel;
        }else if ( cc.sys.os == cc.sys.OS_IOS ){
            return "ios_channel"
            // var nPower = jsb.reflection.callStaticMethod("AppController", "getBatteryPercent");
            // return nPower;
        }else {
            if(CC_DEBUG){
                return "debug"
            }else {
                let params = this.getRequest()
                let tdChannel = params["td_channelid"] || "unknown"
                return tdChannel
            }
        }
    },
    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    start () {

    },

    // update (dt) {},


    postDataFormat:function (obj){
        if(typeof obj != "object" ) {
            cc.log("输入的参数必须是对象");
            return;
        }
        // 支持有FormData的浏览器（Firefox 4+ , Safari 5+, Chrome和Android 3+版的Webkit）
        if(typeof FormData == "function") {
            var data = new FormData();
            for(var attr in obj) {
                data.append(attr,obj[attr]);
            }
            return data;
        }
        else {
            // 不支持FormData的浏览器的处理
            var arr = new Array();
            var i = 0;
            for(var attr in obj) {
                arr[i] = encodeURIComponent(attr) + "=" + encodeURIComponent(obj[attr]);
                i++;
            }
            return arr.join("&");
        }
    },

    async httpRequest (params)
    {
        // cc.log('发送请求', params.url)

        var urlStr = params.url;
        var methodStr = params.method || 'GET'
        var postData = params.postData;
        let async = true

        return new Promise((resolver)=>{
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if(xhr.status >= 200 && xhr.status < 400){
                        if(!!params.callback){
                            params.callback(JSON.parse(xhr.response))
                        }
                        resolver(JSON.parse(xhr.response))
                    }else {
                        let resMsg = JSON.stringify({ succ: false, status: xhr.status, code: 0, data: null, msg: xhr.responseText });
                        resolver(resMsg)
                    }
                }
            };

            xhr.onerror = function (arg0) {
                cc.log('xhr error ', arg0);
            }

            if (!!params.responseType) {
                xhr.responseType = params.responseType;
            }
            xhr.open(methodStr, urlStr, async);

            var tokenStr = params.token;

            if(tokenStr)
            {
                xhr.setRequestHeader("x-access-token",tokenStr)
            }
            if(methodStr === "POST"){
                xhr.setRequestHeader("Content-Type","application/json");
            }

            if(methodStr == "GET"){
                xhr.send();
            }else{
                postData = !postData ? "null" : JSON.stringify(postData)
                // var _postData = this.postDataFormat(postData);
                xhr.send(postData);
            }
        })
    },

    httpGetWithWholeUrl:function (url, queryObj, callback) {
        if(queryObj)
            url = `${url}?${this.parseParams(queryObj)}`;

        let params = {
            method:"GET",
            url:url,
            postData:null,
            callback:callback,
            token:this.USER_TOKEN
        }
        this.httpRequest(params)
    },

    async httpGet (url,queryObj,callback) {
        if(queryObj)
            url = `${url}?${this.parseParams(queryObj)}`;

        let params = {
            method:"GET",
            url:this.rootUrl + url,
            postData:null,
            callback:callback,
            token:this.USER_TOKEN
        }
        cc.log("发送请求url:",url)
        return await this.httpRequest(params)
    },

    async httpPost (url,postData,callback) {
        let params = {
            method:"POST",
            url:this.rootUrl + url,
            postData:postData,
            callback:callback,
            token:this.USER_TOKEN
        }
        return await this.httpRequest(params)
    },


    parseParams:function (query = {}) {
        let params = [];
        if (query instanceof Object) {
            Object.keys(query).forEach(k => {
                params.push(`${encodeURIComponent(k)}=${encodeURIComponent(query[k])}`);
            });
        }
        return params.join('&');
    },

    setUserToken:function(token) {
        this.USER_TOKEN = token;
    }
});
